package com.mlan.userap.untils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.OpenableColumns;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.mlan.userap.AppConfig;
import com.mlan.userap.MyAPP;
import com.mlan.userap.model.AppInfo;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;

public class CommTool {
    /**
     * 获取文件类型
     * @param url   上传成功后的url
     * @return
     */
    public static int getMesType(String url){
        int pos=url.lastIndexOf(".");
        if(pos>0){
            String extMusic=".MP3; .AAC; .WAV; .WMA; .CDA; .FLAC; .M4A; .MID; .MKA; .MP2; .MPA; .MPC; .APE; .OFR; .OGG; .RA; .WV; .TTA; .AC3; .DTS";
            String extVedio=".AVI; .WMV; .MPG; .MOV; .RM; .MP4; ";
            String extImage=".JPEG; .GIF; .BMP; .PNG; .JPG;";
            String extension = url.substring(pos).toUpperCase();
            if(extMusic.indexOf(extension)>=0)
                return 7;
            else if(extVedio.indexOf(extension)>=0)
                return 4;
            else if(extImage.indexOf(extension)>=0)
                return 2;
            else
                return 5;
        }
        return  0;
    }
    public static void showToast(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * 将url进行encode，解决部分手机无法下载含有中文url的文件的问题（如OPPO R9）
     *
     * @param url
     * @return
     * @author xch
     */
    public static String toUtf8String(String url) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < url.length(); i++) {
            char c = url.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
    /**
     * 将毫秒数转为日期格式
     *
     * @param timeMillis
     * @return
     */
    private String formatTime(String timeMillis) {
        long timeMillisl=Long.parseLong(timeMillis);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillisl);
        return simpleDateFormat.format(date);
    }
    public static boolean isLocalExist(String resUrl) {
        return getLocalFile(resUrl).exists();
    }

    public static File getLocalFile(String resUrl) {
        String mFileName = getSaveName(resUrl);
        String path = getSaveDir();
        return new File(path,mFileName);
    }
    public static String getSaveDir() {
        String path;

        if (Build.VERSION.SDK_INT > 29) {
            path = MyAPP.getContext().getExternalFilesDir(null).getAbsolutePath() + "/taskres/";
        } else {
            path = Environment.getExternalStorageDirectory().getPath() + "/taskres/";
        }
        File file=new File(path);
        if(!file.exists())  file.mkdir();
        Log.e("getSaveDir",path);
        return path;
    }
    public static String getSaveName(String resUrl) {
        int sindex = resUrl.lastIndexOf(".");
        String ext = resUrl.substring(sindex);
        String mFileName = MD5Util.encoder(resUrl);
        String filename=mFileName+ext;
        Log.e("getSaveName",filename);
        return  filename;
    }
    /**
     * 将字节数转换为KB、MB、GB
     *
     * @param size 字节大小
     * @return
     */
    public static String formatKMGByBytes(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.00");
        if (size >= 1024 * 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024 * 1024) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024) {
            if (size <= 0) {
                bytes.append("0B");
            } else {
                bytes.append((int) size).append("B");
            }
        }
        return bytes.toString();
    }

    public static String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private static final String[][] MIME_MapTable = {
            // {后缀名，MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx",
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"}, {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"},
            {".sh", "text/plain"}, {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"}, {".txt", "text/plain"},
            {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"}, {"", "*/*"}};

    public static String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String formatTimestamp(long timestamp) {
        // 将13位时间戳转换为 Date
        Date date = new Date(timestamp);
        Calendar messageCal = Calendar.getInstance();
        messageCal.setTime(date);

        Calendar nowCal = Calendar.getInstance();

        // 当天显示 "小时:分"
        if (isSameDay(messageCal, nowCal)) {
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
            return timeFormat.format(date);
        }

        // 当周显示 "星期几"
        if (isSameWeek(messageCal, nowCal)) {
            SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("E", Locale.getDefault());
            return dayOfWeekFormat.format(date).replace("星期", "周"); // 替换"星期"为"周"
        }

        // 当年显示 "MM月dd日"
        if (isSameYear(messageCal, nowCal)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日", Locale.getDefault());
            return dateFormat.format(date);
        }

        // 否则显示 "yyyy年MM月dd日"
        SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return fullDateFormat.format(date);
    }

    // 判断是否是同一天
    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
    }

    // 判断是否是同一周
    private static boolean isSameWeek(Calendar cal1, Calendar cal2) {
        // 创建副本以避免修改原始Calendar对象
        Calendar c1 = (Calendar) cal1.clone();
        Calendar c2 = (Calendar) cal2.clone();

        // 设置周的第一天为星期一
        c1.setFirstDayOfWeek(Calendar.MONDAY);
        c2.setFirstDayOfWeek(Calendar.MONDAY);

        // 设置最小天数为4，确保完整的一周
        c1.setMinimalDaysInFirstWeek(4);
        c2.setMinimalDaysInFirstWeek(4);

        return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
                c1.get(Calendar.WEEK_OF_YEAR) == c2.get(Calendar.WEEK_OF_YEAR);
    }

    // 判断是否是同一年
    private static boolean isSameYear(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
    }

    /**
     * 获取文件后缀名称
     * @param context
     * @param uri
     * @return
     */
    public static String getFileExtensionFromUri(Context context, Uri uri) {
        String fileExtension = "";
        String fileName = null;

        // 检查 Uri 是否是 content:// 类型
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        fileName = cursor.getString(nameIndex);
                    }
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 file:// 类型，直接从路径中获取文件名
            fileName = uri.getLastPathSegment();
        }

        // 从文件名中提取后缀
        if (fileName != null && fileName.contains(".")) {
            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        }

        return fileExtension;
    }

    public static String getFileNameFromUri(Context context, Uri uri) {
        String fileName = null;

        // 检查是否是 content:// 类型
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        fileName = cursor.getString(nameIndex);
                    }
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 对于 file:// 类型，直接从路径中提取文件名
            fileName = uri.getLastPathSegment();
        }

        // 如果无法获取文件名，返回默认值或 null
        return fileName != null ? fileName : "unknown_file";
    }
    /**
     *
     * @param packname 包名
     * @param state 1 设置  2 取消
     */
    public static void setWhiteAPP(String packname,int state){
        List<String> strexists = getWhiteAPP();
        boolean ib_exists=false;
        for (String str :  strexists) {
            if(str.equals(packname)){
                ib_exists=true;
            }
        }
        if(ib_exists&&state==2){
            strexists.remove(packname);
        }
        if(!ib_exists&&state==1){
            strexists.add(packname);
        }
        String newWhiteapp = String.join(";",strexists);
        Log.e("TAG", "setWhiteAPP: "+newWhiteapp);
        Settings.Global.putString(MyAPP.getContext().getContentResolver(),"mlanWhitePacks",newWhiteapp);

    }
    public static List<String> getWhiteAPP(){
        List<String> rtn = new ArrayList<String>();
        String packs = Settings.Global.getString(MyAPP.getContext().getContentResolver(),"mlanWhitePacks");
        Log.e("TAG", "getWhiteAPP: "+packs);
        if(packs!=null&&!packs.isEmpty()&&packs.length()>0){
            String[] temp=  packs.split(";");
            if(temp!=null&&temp.length>0) {
                for (String str :  temp) {
                    rtn.add(str);
                }
            }
        }
        return rtn;
    }
    public static String getIMEI(){
        TelephonyManager tm = (TelephonyManager) MyAPP.getApp().getSystemService(Context.TELEPHONY_SERVICE);
        if(tm == null) return  "";
        String imei = tm.getImei(0);
        Log.e("TAG", "imei: "+imei);
        return imei;
    }

    public static ArrayList<AppInfo> getAppInfo(){
        ArrayList<AppInfo> appBeanList = new ArrayList<>();
        AppInfo bean = null;
        String [] exist_appinfo = getSharedConfig("appinfo").split(";");
        List<String> list_whiteAPP =  getWhiteAPP();
        PackageManager packageManager = MyAPP.getContext().getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (PackageInfo p : list) {
            int flags = p.applicationInfo.flags;
            if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                continue;
            } else {
                bean = new AppInfo();
                String packname=p.applicationInfo.packageName;
                bean.setPackagename(packname);
                boolean needIcon=true;
                for (String str :  exist_appinfo) {
                    if(str.equals(packname)){
                        needIcon=false;
                        break;
                    }
                }
                if(needIcon){
                    bean.setAppname(packageManager.getApplicationLabel(p.applicationInfo).toString());
                    bean.setAppicon(getIconStr(packageManager,p.applicationInfo.packageName));
                }
                for (String str :  list_whiteAPP) {
                    if(str.equals(packname)){
                        bean.setWhiteApp(1);
                        break;
                    }
                }
                appBeanList.add(bean);
            }
        }
        return appBeanList;
    }
    public static Bitmap BitScreen() {
        Bitmap bitmap=null;
        try {
            WindowManager wm = (WindowManager) MyAPP.getContext().getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            DisplayMetrics dm = new DisplayMetrics();
            display.getRealMetrics(dm);

            int screenWidht= dm.widthPixels;
            int screenHeight= dm.heightPixels;
            long t1 = System.currentTimeMillis();
            Class<?>  demo = Class.forName("android.view.SurfaceControl");
            Method method=demo.getMethod("screenshot",new Class[]{Rect.class,int.class,int.class,int.class});
            Bitmap  viewMap = (Bitmap) method.invoke(null,new Rect(),screenWidht,screenHeight,0);
            ByteArrayOutputStream  blob =new ByteArrayOutputStream();;
            viewMap.compress(Bitmap.CompressFormat.JPEG,100, blob);
            byte[] bitmapdata = blob.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
            long t2 = System.currentTimeMillis();
            saveBitmap(bitmap,"screen.jpg");
            Log.e("BitScreen",t2-t1+"");
        } catch (Exception e) {
            Log.e("BitScreen",e.getMessage());
        }
        return  bitmap;
    }

    public static String getSharedConfig(String config){
        SharedPreferences sp = MyAPP.getContext().getSharedPreferences("appsetting", 0);
        return sp.getString(config,"");
    }
    public static int getSharedConfigInt(String config){
        SharedPreferences sp = MyAPP.getContext().getSharedPreferences("appsetting", 0);
        return sp.getInt(config,0);
    }
    public static void saveSharedConfigInt(String config,int svalue){
        SharedPreferences sp = MyAPP.getContext().getSharedPreferences("appsetting",  0);
        SharedPreferences.Editor ed = sp.edit();
        ed.putInt(config, svalue);
        ed.commit();
    }
    public static void saveSharedConfig(String config,String svalue){
        SharedPreferences sp = MyAPP.getContext().getSharedPreferences("appsetting",  0);
        SharedPreferences.Editor ed = sp.edit();
        ed.putString(config, svalue);
        ed.commit();
    }
    public static String getIconStr(PackageManager mPackageManager, String packageName){
        Bitmap bitmap = getAppIcon(mPackageManager,packageName);
        if(bitmap==null) return "";
        return bitmapToBase64(bitmap);
    }
    public static String bitmapToBase64(Bitmap bitmap)  {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
        byte[] bytes = baos.toByteArray();
        String myBase64 = Base64.encodeToString(bytes,Base64.NO_WRAP);
        return myBase64;
    }
    public static Bitmap imageScaleMin(Bitmap bitmap,int dst_w,int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();

        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        float min = Math.min(scale_h, scale_w);
        Matrix matrix = new Matrix();
        matrix.postScale(min, min);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix, true);
        return dstbmp;
    }

    public static Bitmap getAppIcon(PackageManager mPackageManager, String packageName) {

        try {
            Drawable drawable = mPackageManager.getApplicationIcon(packageName);

            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            } else {
                //  Log.e("TAG", "width: "+drawable.getIntrinsicWidth()+","+ drawable.getIntrinsicHeight());
                Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                drawable.draw(canvas);
//                bitmap =imageScaleMin(bitmap);
//                saveBitmap(bitmap,packageName+".png");
                return  bitmap;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static boolean saveBitmap(Bitmap bm, String fileName) {
        if (null == bm) {
            return false;
        }
        File foder = new File(Environment.getExternalStorageDirectory() , "ccImage");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            Log.e("TAG", "saveBitmap: "+myCaptureFile.getAbsolutePath());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
            return true;
        } catch (IOException e) {

        }
        return false;
    }
}
